package com.haoshuang.zhouzhoubang.ui.page.order.receiveorder

import android.os.Bundle
import android.view.LayoutInflater
import android.widget.TextView
import com.chad.library.adapter4.BaseQuickAdapter
import com.haoshuang.zhouzhoubang.R
import com.haoshuang.zhouzhoubang.databinding.FragmentReceiveOrderListBinding
import com.haoshuang.zhouzhoubang.model.bean.HomeBean
import com.haoshuang.zhouzhoubang.model.event.RefreshHomeOrderEvent
import com.haoshuang.zhouzhoubang.model.event.RefreshOrderNumEvent
import com.haoshuang.zhouzhoubang.model.event.TakeTaskSuccess
import com.haoshuang.zhouzhoubang.model.event.TransferOrderSuccess
import com.haoshuang.zhouzhoubang.ui.activity.AppointmentCustomerActivity2
import com.haoshuang.zhouzhoubang.ui.activity.BondActivity55
import com.haoshuang.zhouzhoubang.ui.activity.ExaminationActivity2
import com.haoshuang.zhouzhoubang.ui.activity.ExaminationActivity3
import com.haoshuang.zhouzhoubang.ui.activity.SelectSkillsActivity3
import com.haoshuang.zhouzhoubang.ui.dialog.BgxDialog
import com.haoshuang.zhouzhoubang.ui.dialog.ConfirmDialog
import com.haoshuang.zhouzhoubang.ui.dialog.QdDialog
import com.haoshuang.zhouzhoubang.ui.dialog.QdDialog2
import com.haoshuang.zhouzhoubang.ui.dialog.QdDialog3
import com.haoshuang.zhouzhoubang.ui.dialog.ShowOrderPriceDialog
import com.haoshuang.zhouzhoubang.ui.dialog.ShowRewardNoticeDialog
import com.haoshuang.zhouzhoubang.ui.dialog.TisKsDialog
import com.haoshuang.zhouzhoubang.ui.dialog.Ts10Dialog
import com.haoshuang.zhouzhoubang.ui.dialog.Tx2Dialog
import com.haoshuang.zhouzhoubang.ui.page.home.settings.rate.TeamRateSetActivity
import com.haoshuang.zhouzhoubang.ui.page.main.MainActivity
import com.haoshuang.zhouzhoubang.ui.page.order.receiveorder.detail.ReceiveOrderDetailActivity
import com.haoshuang.zhouzhoubang.utils.MediaPlayUtils
import com.jeremyliao.liveeventbus.LiveEventBus
import com.lnkj.jialubao.utils.AccountUtils
import com.lxj.xpopup.XPopup
import com.mufeng.libs.base.BaseVMFragment
import com.mufeng.libs.core.finishAll
import com.mufeng.libs.core.setOnItemChildClick
import com.mufeng.libs.core.setOnItemClick
import com.mufeng.libs.state.observeState
import com.mufeng.libs.utils.startPage
import com.mufeng.libs.utils.toast
import com.mufeng.libs.utils.view.clickWithTrigger
import com.mufeng.libs.utils.view.vertical

fun BaseQuickAdapter<*, *>.setEmptyOrder(
    reRefreshData: () -> Unit = {},
    toStudy: () -> Unit = {},
) {

    val emptyView = LayoutInflater.from(context).inflate(R.layout.order_take_empty_layout, null)
    val tvToStudy = emptyView.findViewById<TextView>(R.id.tvToStudy)
    val tvRefresh = emptyView.findViewById<TextView>(R.id.tvRefresh)
    tvToStudy.clickWithTrigger {
        toStudy()
    }

    tvRefresh.clickWithTrigger {
        reRefreshData()
    }

    this.stateView = emptyView
    isStateViewEnable = false

}

/**
 *  待接单页面列表
 */
class ReceiveOrderListFragment :
    BaseVMFragment<ReceiveOrderListViewModel, FragmentReceiveOrderListBinding>() {

    companion object {
        fun getInstance(): ReceiveOrderListFragment {
            val fragment = ReceiveOrderListFragment()
            fragment.arguments = Bundle().apply {

            }
            return fragment
        }
    }

    // 选中操作的任务
    private var chooseOrder: HomeBean? = null

    /**
     * 入驻状态 进度
     */
    private var masterState = "0"

    // 不感兴趣标签
    private val unlikeTagList = arrayListOf<String>()

    // 抢单列表
    private val data = arrayListOf<HomeBean>()
    private val adapter = ReceiveOrderListAdapter(data)

    private var cate_id = 0
    private var tcate_id = 0

    override fun initView(savedInstanceState: Bundle?) {

        binding.recyclerView.vertical()
            .adapter = adapter
        adapter.setEmptyOrder(
            reRefreshData = {
                binding.refreshLayout.autoRefresh()
            }, toStudy = {
                (mActivity as MainActivity).startStudyPage()
            }
        )
        adapter.setOnItemChildClick(id = R.id.tvReceiveOrder) { view, position, item ->
            if (item == null) return@setOnItemChildClick
            chooseOrder = item
            vm.verifyTakeTask(item.id.toString())

        }
        adapter.setOnItemChildClick(id = R.id.tvUninterested) { view, position, item ->
            if (item == null) return@setOnItemChildClick
            XPopup.Builder(requireContext())
                .asCustom(BgxDialog(requireContext(), unlikeTagList) { tag, remark ->
                    vm.addUnlikeOrder(item.id.toString(), tag, remark)
                })
                .show()
        }
        adapter.setOnItemChildClick(id = R.id.llRewardView) { view, position, item ->
            if (item == null) return@setOnItemChildClick
            XPopup.Builder(mActivity)
                .asCustom(ShowRewardNoticeDialog(mActivity))
                .show()
        }
        adapter.setOnItemChildClick(id = R.id.llPrice) { view, position, item ->
            if (item == null) return@setOnItemChildClick
            XPopup.Builder(mActivity)
                .asCustom(
                    ShowOrderPriceDialog(
                        context = mActivity,
                        prepayments_amount = item.prepayments_amount.toString(),
                        nightPrice = "${item.nighttime_amount}",
                        totalPrice = item.pay_price,
                        teamPrice = "",
                        teamLeaderPrice = "",
                        teamMemberPrice = "",
                        minePrice = item.pay_price,
                    )
                )
                .show()
        }

        adapter.setOnItemClick { view, position, item ->
            if (item == null) return@setOnItemClick
            // 点击看接单详情
            startPage<ReceiveOrderDetailActivity>("order_id" to item.id.toString())
        }

        binding.refreshLayout.setOnRefreshListener {
            p = 1
            isShowing = false
            vm.getMasterTaskList(p)
        }

    }

    override fun initData() {
        // 获取不感兴趣的理由
        vm.getUnlikeTag()
    }

    override fun lazyLoadData() {
        p = 1
        vm.getMasterTaskList(p)
    }

    fun refreshData() {
        binding.refreshLayout.autoRefresh()
    }

    override fun startObserve() {
        LiveEventBus.get("BJg", Boolean::class.java).observe(this) {
            XPopup.Builder(mActivity)
                .asCustom(TisKsDialog(mActivity, "很遗憾认证未通过") {
                    startPage<ExaminationActivity2>("ids" to tcate_id, "ids2" to cate_id)
                }).show()
        }
        LiveEventBus.get(
            RefreshHomeOrderEvent::class.java
        ).observe(this) {
            p = 1
            vm.getMasterTaskList(p)
        }
        /// 转单成功事件
        LiveEventBus.get(TransferOrderSuccess::class.java).observe(this) {
            p = 1
            vm.getMasterTaskList(p)
        }

        // 获取不感兴趣标签
        vm.getUnlikeTagData.observeState(this) {
            onSuccess {
                unlikeTagList.clear()
                unlikeTagList.addAll(it ?: mutableListOf())
            }
        }

        // 获取抢单任务列表
        vm.getMasterTaskListData.observeState(this) {
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                binding.refreshLayout.finishAll()
                LiveEventBus.get(RefreshOrderNumEvent::class.java).post(RefreshOrderNumEvent)
                data.clear()
                data.addAll(it!!)
                adapter?.notifyDataSetChanged()
                adapter.isStateViewEnable = true
            }
        }

        vm.addUnlikeOrderData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                toast(msg)
            }
            onSuccess {
                dismissLoading()
                binding.refreshLayout.autoRefresh()
            }
        }

        vm.verifyTakeTaskData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                if (code == "1003") {
                    XPopup.Builder(requireContext())
                        .asCustom(Tx2Dialog(requireContext()) {
                            if (it == 0) {
                                val baoXianFee =
                                    if (AccountUtils.user?.insurance_status == "1" && AccountUtils.user?.insurance_type == "1") chooseOrder?.deduct_insurance_amount else null

                                if (chooseOrder?.is_cart_order == 1) {
                                    XPopup.Builder(requireContext())
                                        .asCustom(
                                            QdDialog3(
                                                requireContext(),
                                                chooseOrder,
                                                baoXianFee ?: ""
                                            ) {
                                                vm.masterTakeTask(chooseOrder?.id.toString())
                                            })
                                        .show()
                                } else {
                                    XPopup.Builder(requireContext())
                                        .asCustom(
                                            QdDialog2(
                                                requireContext(),
                                                chooseOrder?.pay_price ?: "",
                                                baoXianFee
                                            ) {
                                                vm.masterTakeTask(chooseOrder?.id.toString())
                                            })
                                        .show()
                                }


                            } else {
                                startPage<BondActivity55>(
                                    "team_id" to (AccountUtils.user?.team_id?.toIntOrNull() ?: 0)
                                )
                            }

                        })
                        .show()
                } else if (code == "1002") {
                    // 当门店未设置分成比例时接单提示
                    XPopup.Builder(context)
                        .asCustom(
                            ConfirmDialog(
                                context = mActivity,
                                title = "温馨提示",
                                content = "您创建的门店当前未设置分成比例\n无法进行抢单，请设置后在进行抢单",
                                cancelStr = "取消",
                                confirmStr = "去设置",
                                isHideCancel = false,
                                onCancel = {},
                                onConfirm = {
                                    startPage<TeamRateSetActivity>()
                                })
                        )
                        .show()
                } else {
                    toast(msg)
                }

            }
            onSuccess {
                dismissLoading()
                val baoXianFee =
                    if (AccountUtils.user?.insurance_status == "1" && AccountUtils.user?.insurance_type == "1") chooseOrder?.deduct_insurance_amount else null
               /* XPopup.Builder(requireContext())
                    .asCustom(
                        QdDialog2(
                            requireContext(),
                            chooseOrder?.pay_price ?: "",
                            baoXianFee
                        ) {
                            vm.masterTakeTask(chooseOrder?.id.toString())
                        })
                    .show()*/

                if (chooseOrder?.is_cart_order == 1) {
                    XPopup.Builder(requireContext())
                        .asCustom(
                            QdDialog3(
                                requireContext(),
                                chooseOrder,
                                baoXianFee ?: ""
                            ) {
                                vm.masterTakeTask(chooseOrder?.id.toString())
                            })
                        .show()
                } else {
                    XPopup.Builder(requireContext())
                        .asCustom(
                            QdDialog2(
                                requireContext(),
                                chooseOrder?.pay_price ?: "",
                                baoXianFee
                            ) {
                                vm.masterTakeTask(chooseOrder?.id.toString())
                            })
                        .show()
                }
            }
        }

        vm.masterTakeTaskData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                if ("未认证当前服务技能" == msg) {
                    XPopup.Builder(requireContext())
                        .asCustom(
                            Ts10Dialog(
                                requireContext()
                            ) {
                                vm.masterGetSkill(chooseOrder?.id.toString())
                            })
                        .show()
                } else {
                    toast(msg)
                }

            }
            onSuccess {
                dismissLoading()
                // 播放抢单成功音频
                MediaPlayUtils.playTakeOrderSuccess()
                // 发送抢单成功事件
                LiveEventBus.get(TakeTaskSuccess::class.java).post(TakeTaskSuccess())
                XPopup.Builder(requireContext())
                    .asCustom(
                        QdDialog(
                            requireContext(),
                            it?.confirm_residue_time!!
                        ) {
                            if (chooseOrder?.is_team == "0") {
                                startPage<AppointmentCustomerActivity2>(
                                    "ids" to it.oid
                                )
                            } else {
                                startPage<AppointmentCustomerActivity2>(
                                    "ids" to it.oid
                                )
                            }

                        })
                    .show()
                binding.refreshLayout.autoRefresh()
            }
        }

        vm.masterGetSkillData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()

            }
            onSuccess {
                dismissLoading()
                if (it != null) {
                    if (chooseOrder?.is_team == "0") {
                        cate_id = it.cate_id
                        tcate_id = it.tcate_id
                        vm.verifyService(it.cate_id.toString(), it.tcate_id.toString())
                    } else {
                        startPage<SelectSkillsActivity3>(
                            "cate_id" to it.cate_id,
                            "tcate_id" to it.tcate_id,
                            "fcate_id" to it.fcate_id
                        )
                    }
                }

            }
        }

        vm.verifyServiceData.observeState(this) {
            onLoading { showLoading() }
            onError { code, msg ->
                dismissLoading()
                if (code != "402") {
                    toast(msg)
                }
            }
            onSuccess {
                dismissLoading()
                startPage<ExaminationActivity3>("ids" to tcate_id, "ids2" to cate_id)
            }
        }

    }

}